package crawler;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

public class Main
{    
	private static GnutellaGraph mGraph;	
	
	private static void PrintUsage()
	{
		System.out.println("Error: incorrect inputs");
		System.out.println("Usage: crawler <host:port> <time>");
		System.out.println("  <host:port> is the node to be used as a bootstrapping point");
		System.out.println("  <time> is the length of time after which to stop crawling");
		System.out.println("    *** note: time is in milliseconds and must be >= 0");
		System.out.println("              after this time, no new queries will be issued");
		System.out.println("\n");
	}

    public static void main(String[] args)
    {
        String nodeAddress=new String();
        int nodePort=0;
        long timeout = 0;
        
    	try
    	{
    		if(args.length != 2)
    		{
    			PrintUsage();
    			return;
    		}
    	
    		String tokens[] = args[0].split(":");
    		if(tokens.length != 2)
    		{
    			PrintUsage();
    			return;
    		}
    	
    		nodeAddress = tokens[0];
    		nodePort = Integer.parseInt(tokens[1]);
    		
    		timeout = Long.parseLong(args[1]);
    		
    		if(timeout <= 0 )
    		{
    			PrintUsage();
    			return;
    		}
    	}
    	catch(Exception e)
    	{
    		PrintUsage();
    		return;
    	}

		Date start = new Date();
    	
        CrawlerVector mainCrawler=new CrawlerVector();
        mGraph = new GnutellaGraph(512, 512);
        
        CrawlResultVector bootstrapResult = mainCrawler.crawlvector(nodeAddress,nodePort);
        
        if(bootstrapResult == null)
        {
        	System.out.println("Unable to crawl the bootstrap node.");
        	return;
        }
        
        ProcessResult(bootstrapResult);
        
        while((new Date().getTime() - start.getTime()) < timeout)
        {
        	String addressAndPort = mGraph.GetAddressToCrawl();
        	if(addressAndPort == null)
        	{
        		System.out.println("Could not find node to crawl...");
        		return;
        	}
        	
    		String tokens[] = addressAndPort.split(":");
    	
    		nodeAddress = tokens[0];
    		nodePort = Integer.parseInt(tokens[1]);
        	
        	CrawlResultVector newResult = mainCrawler.crawlvector(nodeAddress, nodePort);
        	if(newResult == null)
        	{
        		mGraph.NotifyCrawlFailure(addressAndPort);
        		continue;
        	}
        	//newResult.PrintResult();
        	ProcessResult(newResult);
        }
       
        System.out.println("Timeout reached");
    }   
   
    private static void ProcessResult(CrawlResultVector result)
    {
    	//result.PrintResult();
    	mGraph.ProcessResult(result);
    	mGraph.GenerateHTML("WWW");
    	//mGraph.DrawToFile("TestImage");
    }
}
